<?php
namespace CRM\Util;
use Common\Util\HttpsConnection;
use Think\Db;
use Think\Log;

class WXWorkMessage extends HttpsConnection{
    public $corpID;
    public $agentID;
    public $userID;//正在对话的用户ID
    function __construct(){
        $this->corpID=C("WXWork_CorpID");
        $this->agentID=C("WXWork_AgentId");
        $key=C("WXWorkMessage_Key");
        $token=C("WXWorkMessage_Token");

        vendor('WXWork.callback.WXBizMsgCrypt');
        $this->crypt=new \WXBizMsgCrypt($token, $key, $this->corpID);
    }
    protected function stringifyData($data){
        $content=json_encode($data);
        return $content;
    }
    protected function parseData($content){
        $data=json_decode($content,true);
        return $data;
    }
    //用来证明这个服务器有效的接口
    public function testifyMessageInterface($data){
        Log::write("验证消息回调接口有效性:".json_encode($data,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE),Log::DEBUG);
        $signature = $data["msg_signature"];
        $timestamp = $data["timestamp"];
        $nonce = $data["nonce"];
        $echostr=$data["echostr"];
        $echostr = str_replace(" ","+",$echostr);
        $echostr = str_replace("\/","/",$echostr);
        $message = "";
        $errCode = $this->crypt->VerifyURL($signature, $timestamp, $nonce, $echostr, $message);
        if ($errCode == 0) {
            Log::write("验证消息:".$message,Log::DEBUG);
            echo $message;
        } else {
            print("ERR: " . $errCode . "\n\n");
            Log::write("ERR:".$errCode,Log::DEBUG);
        }
    }
    //用来接受消息的接口
    public function receiveMessage(){
        Log::write("接收到加密消息:".json_encode($_GET,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE),Log::DEBUG);
        $signature = $_GET["msg_signature"];//"477715d11cdb4164915debcba66cb864d751f3e6";
        $timestamp = $_GET["timestamp"];//"1409659813";
        $nonce = $_GET["nonce"];//"1372623149";
        $data = file_get_contents("php://input");//"<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>";
        $decrypted = "";  // 解析之后的明文
        Log::write($data,Log::DEBUG);
        $errCode = $this->crypt->DecryptMsg($signature, $timestamp, $nonce, $data, $decrypted);
        if ($errCode == 0) {
            Log::write("解密消息:".$decrypted,Log::DEBUG);
            $xml = new \DOMDocument();
            $xml->loadXML($decrypted);
            $this->userID=$xml->getElementsByTagName('FromUserName')->item(0)->nodeValue;
            $this->agentID=$xml->getElementsByTagName('AgentID')->item(0)->nodeValue;
            $message=$xml->getElementsByTagName('Content')->item(0)->nodeValue;
            Log::write("提取消息内容:".$decrypted,Log::DEBUG);
            return $message;
        } else {
            print("ERR: " . $errCode . "\n\n");
            Log::write("ERR:".$errCode,Log::DEBUG);
        }
    }
    //被动回复消息
    public function replyMessage($message){
        Log::write("自动回复消息:".$message,Log::DEBUG);
        $timestamp=time();
        $nonce=rand(100000,999999);
        $data = '<xml>
            <ToUserName><![CDATA['.$this->userID.']]></ToUserName>
            <FromUserName><![CDATA['.$this->corpID.']]></FromUserName>
            <CreateTime>'.$timestamp.'</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA['.$message.']]></Content>
            <MsgId>1234567890123456</MsgId>
            <AgentID>'.$this->agentID.'</AgentID>
        </xml>';
        Log::write($data,Log::DEBUG);
        $encrypted = ""; //xml格式的密文
        $errCode = $this->crypt->EncryptMsg($data, $timestamp, $nonce, $encrypted);
        if ($errCode == 0) {
            echo $encrypted;
        } else {
            print("ERR: " . $errCode . "\n\n");
        }
        Log::write("处理结果:".$errCode,Log::DEBUG);
    }
}